package com.eqxiu.ieditor.msg.event;

import com.eqxiu.common.mapper.JsonMapper;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author suixiangyu
 */
@Component
public class HandleSceneStatusEventListener {

    private final Logger LOGGER = LoggerFactory.getLogger(HandleSceneStatusEventListener.class);

    @Autowired(required = false)
    private RabbitTemplate rabbitTemplate;

    @Value("${rabbitmq.handleScene.exchange}")
    private String exchange;

    @Value("${rabbitmq.handleScene.routingKey}")
    private String routingKey;

    @Async
    @EventListener(condition = "#event.shouldSendMsg")
    public void handleEvent(HandleSceneStatusEvent event) {
        try {
            LOGGER.info("======handle SceneStatusEvent begin========");
            Map<String, Object> message = new HashMap<>(16);
            message.put("userId", event.getUserId());
            message.put("sceneId", event.getSceneId());
            message.put("status", event.getStatus());
            LOGGER.info("======SceneStatusEvent message========" + new Gson().toJson(message));
            String s = JsonMapper.getInstance().toJson(message);
            rabbitTemplate.convertAndSend(exchange, routingKey, s);
            LOGGER.info("======handle SceneStatusEvent success========");
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
    }
}
